<template>
  <div>
    <div ref="container" id="container"></div>
  </div>
</template>

<script setup>
import { MMDAnimationHelper } from "three/examples/jsm/animation/MMDAnimationHelper.js";
import { MMDLoader } from "three/examples/jsm/loaders/MMDLoader.js";
import * as THREE from "three";
import { onMounted, reactive, ref } from "vue";

const container = ref(null);

let scene, camera, renderer, clock;
let frameId;

onMounted(() => {
  // 相机位置的响应式数据
  const cameraPosition = reactive({
    x: 0,
    y: 0,
    z: 75,
  });
  const width = window.innerWidth;
  const height = window.innerHeight;
  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera(750, width / height, 0.1, 2000);
  const loader = new MMDLoader();
  const light = new THREE.AmbientLight(0x909090);
  scene.add(light);
  const helper = new MMDAnimationHelper();
  camera.position.set(cameraPosition.x, cameraPosition.y, cameraPosition.z);
  loader.loadWithAnimation(
    "/qque/青雀（分桦）.pmx",
    "/move/ayaka-dance.vmd",
    function onLoad(mmd) {
      // const { mesh } = mmd;
      helper.add(mmd.mesh, {
        animation: mmd.animation,
        physics: false,
      });

      scene.add(mmd.mesh);
    },
    undefined,
    undefined
  );

  renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
  renderer.setSize(width, height);
  // renderer.setClearColor(new THREE.Color(0x000000));
  clock = new THREE.Clock();

  container.value.appendChild(renderer.domElement);

  function animation() {
    frameId = requestAnimationFrame(() => {
      const time = clock.getDelta();
      helper.update(time);
      renderer.render(scene, camera);
    });
  }

  setInterval(() => {
    animation();
  }, 10);
});
</script>

<style scoped></style>
